<?
include_once('class/Exception.class.php');
include_once('class/Config.class.php');

/**
 * $Id: core.php 1184 2008-08-28 13:54:26Z pawy $
 * Klasa jadra aplikacji
 *
 */
class Core {

	private static $version = '1.3.0';

	/**
	 * Dopuszczalne typy stron.. tylko po co?
	 *
	 * @var array
	 */
	private static $site = array('Strona', 'Admin');
	/**
	 * Domyslny szablon glowny
	 * @var string
	 */
	public static $template = 'index.tpl';
	/**
	 * Flaga aplikacji czy jest w trybie awaryjnym
	 * @var bool
	 */
	public static $appSafeMode = false;

	private static $includePaths = array();

	/**
	 * Konstruktor klasy
	 *
	 * @param PageType $site Typ strony
	 */
	public function __construct() {

	}

	/**
	 * Inicjator aplikacji
	 *
	 * @param integer $site
	 */
	public static function Init($site) {
		
		
		include('class/DB.class.php');
		include('class/Registry.class.php');
		self::RequireOnce('class/DbSqlLite.class.php');

		self::LoadConfig($site);
		include('ErrorHandler.php');
        try {
		$db = new DBProd();
		$dbTemp = new DBTemp();
        } catch (MysqlException $e) {
			MFLog::Fatal("Line: ".$e->getLine()." Message: ".$e->getMessage()." Referer: ".getenv('HTTP_REFERER'));
			//var_dump($e);
        }
		Registry::Set('db', $db);
		Registry::Set('dbTemp', $dbTemp);
		Config::Set('site', $site);
		Registry::Set('smartyTemplate', self::$template);
		$title = array();
		Registry::Set('title', $title);
		self::PageConfig();
	}

	public static function SetAppSafeMode() {
		MFLog::Error('Switching into the SafeMod.');
		if(Config::Get('ERROR_REDIRECT')==true) {
			self::$appSafeMode = true;
		}
	}

	public static function GetAppSafeMode() {
		return self::$appSafeMode;
	}

	/**
	 * Parametry konfiguracyjne strony zmieniane przez autora lub administratora
	 *
	 */
	public static function PageConfig() {

//		try {
//		// zaczytuje do rejestru dane z tabeli Setup
//			$config = SetupDAL::GetAllVariables();
//			$rConfig = array();
//			foreach($config as $key=>$value) {
//			    $rConfig[$value['variable']] = array($value['value'], $value['description']);
//			}
//
//			Config::SetDbConfig($rConfig);
//		} catch (MysqlException $e) {
//		    self::SetAppSafeMode();
//		}
//		/*
//		$captchaStatus = true;
//		$moderateStatus = false;		
//		Registry::Set('captchaStatus', $captchaStatus);
//		Registry::Set('moderateStatus', $moderateStatus);
//		*/
//		
//		// ustawienia local dla czasu
//		setlocale(LC_TIME, 'pl_PL.UTF-8', 'pl', 'Polish_Poland.UTF8');

	}


	/**
	 * Ladowanie plikow konfiguracyjnych
	 *
	 * @param PageType $site Typ strony
	 */
	public static function LoadConfig($site) {
		include_once('../config/'.$site.'/path.config.php');
		//include_once('config/'.$site.'/db.config.php');
		include_once('../config/'.$site.'/param.config.php');
		if(!Config::LoadIniConfig('../config/'.$site.'/db.config.ini', true)) {
			include_once('../config/'.$site.'/db.config.php');
		}

	}

	/**
	 * Ladowanie i konfiguracja Smarty
	 *
	 */
	public static function LoadSmarty() {
		require_once('lib/Smarty/Smarty.class.php');
		$smarty = new Smarty();

		//$smarty = new TemplateMaster();

		$smarty->template_dir = Config::Get('PATH_SMARTY_TEMPLATE');
		$smarty->compile_dir = Config::Get('PATH_SMARTY_COMPILE');
		$smarty->cache_dir = Config::Get('PATH_SMARTY_CACHE');
		$smarty->cache_lifetime = 999999999;
		$smarty->caching = Config::Get('SMARTY_CACHING_METHOD');
		$smarty->assign('urlStatic', Config::Get('URL_STATIC_CONTENT'));
		

		
		$smarty->assign('dynamicContent', null);
		$smarty->assign("pageStyle", 'style.css');
		
		$smarty->assign('urlMain', Config::Get('URL_MAIN'));
		$smarty->assign('pageDescription', null);
		
		Registry::Set('smarty', $smarty);
	}

	/**
	 * Wyswietla szablon Smarty
	 *
	 * @return Wgenerowana strona
	 */
	public static function SmartyDisplay() {
		$smarty = Registry::Get('smarty');
		return $smarty->display(self::$template);
	}


	/**
	 * Laduje pliki z klasami
	 *
	 * @param $name Nazwa pozadanej klasy
	 */
	public static function LoadClass($name) {
		if (file_exists(Config::Get('PATH_CORE').'/../modules/'.$name.'.class.php')) {
			self::RequireOnce(Config::Get('PATH_CORE').'/../modules/'.$name.'.class.php');
		} else if(file_exists(Config::Get('PATH_CORE').'/class/'.$name.'.php')) {
			self::RequireOnce(Config::Get('PATH_CORE').'/class/'.$name.'.php');
		} else if (file_exists('module/'.$name.'.mod.php')){
			self::RequireOnce('module/'.$name.'.mod.php');
		} else if (file_exists(Config::Get('PATH_CORE').'/model/'.$name.'.php')) {
			self::RequireOnce(Config::Get('PATH_CORE').'/model/'.$name.'.php');
		} else if (file_exists(Config::Get('PATH_CORE').'/../model/'.$name.'.php')) {
			self::RequireOnce(Config::Get('PATH_CORE').'/../model/'.$name.'.php');
		} else if (file_exists(Config::Get('PATH_CORE').'/lib/'.$name.'.class.php')) {
			self::RequireOnce(Config::Get('PATH_CORE').'/lib/'.$name.'.class.php');
		} else if (file_exists(Config::Get('PATH_CORE').'/../lib/'.$name.'.class.php')) {
			self::RequireOnce(Config::Get('PATH_CORE').'/../lib/'.$name.'.class.php');
		} else if (file_exists(PATH_CORE.'/model/'.strtolower(str_replace('DAL', '', $name)).'/'.$name.'.class.php')) {
			include(PATH_CORE.'/model/'.strtolower(str_replace('DAL', '', $name)).'/'.$name.'.class.php');
		} else {
           
			preg_match_all('/[A-Z]/', $name,$matches);

			if(isset($matches[0][1]))
			{

				$firstChar = substr($name,0,1);
				$fullpathArray = explode($matches[0][1],substr($name,1),2);
				$fullpathFile = '../model/'. strtolower($firstChar) .	$fullpathArray[0] . '/' . $matches[0][1] . $fullpathArray[1] .'.php';
				if (file_exists($fullpathFile))
				{
					include($fullpathFile);
				}
				else
				{
				    $fullpathFile = '../core/class/'. strtolower($firstChar) .	$fullpathArray[0] . '/' . $matches[0][1] . $fullpathArray[1] .'.php';
				    if (file_exists($fullpathFile))
				    {
					    include($fullpathFile);
				    }				    
				}
			}

			$path = str_replace('_', '/', $name);


			if(file_exists(Config::Get('PATH_CORE').'/'.$path.'.class.php')) {
				self::RequireOnce(Config::Get('PATH_CORE').'/'.$path.'.class.php');
			} else if(file_exists(Config::Get('PATH_CORE').'/model/'.$path.'.class.php')) {
				self::RequireOnce(Config::Get('PATH_CORE').'/model/'.$path.'.class.php');
			} else if(file_exists(Config::Get('PATH_CORE').'/lib/'.$path.'.class.php')) {
				self::RequireOnce(Config::Get('PATH_CORE').'/lib/'.$path.'.class.php');
			} else foreach (self::$includePaths as $includePath) {
				if (file_exists($includePath . '/' . $path . '.php')) {
					self::RequireOnce($includePath . '/' . $path . '.php');
				}
			}
 
		} 
	}


	public static function SetIncludePaths(Array $incluePaths) {
		self::$includePaths = $incluePaths;
	}

	public static function GetIncludePaths() {
		return self::$includePaths;
	}

	public static function RemoveIncludePath($includePath) {
		$i = array_search($includePath, self::$includePaths);

		if ($i !== false) {
			unset(self::$includePaths[$i]);
		}
	}

	public static function AddIncludePath($includePath) {
		if (!in_array($includePath, self::$includePaths)) {
			self::$includePaths[] = $includePath;
		}
	}
	
	/**
	 * Zamyka aplikacje
	 *
	 */
	public static function Garbage() {
		$db = Registry::Get('db');
		$db=NULL;
	}

    public static function RequireOnce($file) {
        require_once($file);
    }

    public static function LoadPlugin($plugin) {
        self::RequireOnce('plugins/'.$plugin.'.php');
    }


	public static function getVersion() {
		return self::$version;
	}

}
/**
 * Klasa wyboru typu aplikacji
 *
 */
class PageType {
	/**
	 * Część użytkowa
	 *
	 */
	const STRONA = 'Strona';
	/**
	 * Część administracyjna
	 */
	const ADMIN = 'Admin';
	
	/**
	 * Część serwerowa
	 */
	const SERVER = 'Server';
}

/**
 * Bloka dynamiczny jako funkcja do smarty
 *
 * @param unknown_type $param
 * @param unknown_type $content
 * @param unknown_type $smarty
 * @return unknown
 */
function SmartyBlockDynamic($param, $content, &$smarty) {
	return $content;
}

/**
 * Zwraca biezacy url
 *
 * @return unknown
 */
function SelfUrl() {
    $s = empty($_SERVER["HTTPS"]) ? '' : ($_SERVER["HTTPS"] == "on") ? "s" : "";
    $protocol = StrLeft(strtolower($_SERVER["SERVER_PROTOCOL"]), "/").$s;
    $port = ($_SERVER["SERVER_PORT"] == "80") ? "" : (":".$_SERVER["SERVER_PORT"]);
	return $protocol."://".$_SERVER['SERVER_NAME'].$port.$_SERVER['REQUEST_URI'];
}
/**
 * Funkcja pomocnicza do SelfUrl()
 *
 * @param unknown_type $s1
 * @param unknown_type $s2
 * @return unknown
 */
function StrLeft($s1, $s2) {
    return substr($s1, 0, strpos($s1, $s2));
} 
